package controllers

import (
	"encoding/json"
	"strconv"
	"supershare/backend/models"
	"time"

	"github.com/beego/beego/v2/server/web"
)

// PaymentChannelController 支付渠道控制器
type PaymentChannelController struct {
	web.Controller
}

// handleError 统一错误处理
func (c *PaymentChannelController) handleError(err error, message string) {
	c.Data["json"] = map[string]interface{}{
		"success": false,
		"message": message,
		"error":   err.Error(),
	}
	c.ServeJSON()
}

// List 获取支付渠道列表
func (c *PaymentChannelController) List() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 获取分页参数
	page, _ := c.GetInt("page", 1)
	pageSize, _ := c.GetInt("pageSize", 10)

	// 获取过滤参数
	filters := make(map[string]interface{})

	if name := c.GetString("name"); name != "" {
		filters["name"] = name
	}

	if code := c.GetString("code"); code != "" {
		filters["code"] = code
	}

	if channelType := c.GetString("type"); channelType != "" {
		filters["type"] = channelType
	}

	if status, err := c.GetInt8("status"); err == nil {
		filters["status"] = status
	}

	// 加盟商只能查看自己的数据
	if permResult.Admin.FranchiseId > 0 {
		filters["franchise_id"] = permResult.Admin.FranchiseId
	}

	// 获取支付渠道列表
	channels, total, err := models.GetPaymentChannelList(page, pageSize, filters)
	if err != nil {
		c.handleError(err, "获取支付渠道列表失败")
		return
	}

	// 转换为前端需要的格式
	var result []map[string]interface{}
	for _, channel := range channels {
		// 解析配置信息
		var config map[string]interface{}
		if channel.Config != "" {
			json.Unmarshal([]byte(channel.Config), &config)
		} else {
			config = make(map[string]interface{})
		}

		// 构建返回数据
		item := map[string]interface{}{
			"id":          channel.Id,
			"name":        channel.Name,
			"code":        channel.Code,
			"type":        channel.Type,
			"icon":        channel.Icon,
			"description": channel.Description,
			"status":      channel.Status,
			"sort_order":  channel.SortOrder,
			"is_default":  channel.IsDefault,
			"created_at":  channel.CreatedAt,
			"updated_at":  channel.UpdatedAt,
		}

		// 将配置信息合并到返回数据中
		for k, v := range config {
			item[k] = v
		}

		result = append(result, item)
	}

	c.Data["json"] = map[string]interface{}{
		"success":  true,
		"data":     result,
		"total":    total,
		"page":     page,
		"pageSize": pageSize,
	}
	c.ServeJSON()
}

// GetOne 获取单个支付渠道信息
func (c *PaymentChannelController) GetOne() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 获取ID参数
	idStr := c.Ctx.Input.Param(":id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的ID参数",
		}
		c.ServeJSON()
		return
	}

	// 获取支付渠道信息
	channel, err := models.GetPaymentChannelById(id)
	if err != nil || channel == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "支付渠道不存在或获取信息失败",
		}
		c.ServeJSON()
		return
	}

	// 验证加盟商权限
	if permResult.Admin.FranchiseId > 0 && channel.FranchiseId != permResult.Admin.FranchiseId {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无权访问此支付渠道",
		}
		c.ServeJSON()
		return
	}

	// 解析配置信息
	var config map[string]interface{}
	if channel.Config != "" {
		json.Unmarshal([]byte(channel.Config), &config)
	} else {
		config = make(map[string]interface{})
	}

	// 构建返回数据
	result := map[string]interface{}{
		"id":          channel.Id,
		"name":        channel.Name,
		"code":        channel.Code,
		"type":        channel.Type,
		"icon":        channel.Icon,
		"description": channel.Description,
		"status":      channel.Status,
		"sort_order":  channel.SortOrder,
		"is_default":  channel.IsDefault,
		"created_at":  channel.CreatedAt,
		"updated_at":  channel.UpdatedAt,
	}

	// 将配置信息合并到返回数据中
	for k, v := range config {
		result[k] = v
	}

	c.Data["json"] = map[string]interface{}{
		"success": true,
		"data":    result,
	}
	c.ServeJSON()
}

// Create 创建支付渠道
func (c *PaymentChannelController) Create() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 解析请求体
	var requestData map[string]interface{}
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &requestData)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求数据",
		}
		c.ServeJSON()
		return
	}

	// 提取支付渠道字段
	name, _ := requestData["name"].(string)
	code, _ := requestData["code"].(string)
	icon, _ := requestData["icon"].(string)
	description, _ := requestData["description"].(string)

	// 检查必填字段
	if name == "" || code == "" {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "名称和代码不能为空",
		}
		c.ServeJSON()
		return
	}

	// 检查代码是否已存在
	existingChannel, _ := models.GetPaymentChannelByCode(code)
	if existingChannel != nil && existingChannel.Id > 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "支付渠道代码已存在",
		}
		c.ServeJSON()
		return
	}

	// 提取状态和排序字段
	status, ok := requestData["status"].(float64)
	if !ok {
		status = 1 // 默认启用
	}
	sortOrder, ok := requestData["sort_order"].(float64)
	if !ok {
		sortOrder = 0 // 默认排序
	}
	isDefault, ok := requestData["is_default"].(float64)
	if !ok {
		isDefault = 0 // 默认不是默认渠道
	}

	// 提取类型字段
	channelType, _ := requestData["type"].(string)

	// 提取配置字段（移除标准字段后的所有内容）
	configData := make(map[string]interface{})
	standardFields := []string{"id", "name", "code", "icon", "description", "status", "sort_order", "is_default", "created_at", "updated_at", "type"}
	for key, value := range requestData {
		isStandardField := false
		for _, field := range standardFields {
			if key == field {
				isStandardField = true
				break
			}
		}
		if !isStandardField {
			configData[key] = value
		}
	}

	// 序列化配置数据
	configJson, err := json.Marshal(configData)
	if err != nil {
		c.handleError(err, "序列化配置数据失败")
		return
	}

	// 创建支付渠道
	channel := &models.PaymentChannel{
		Name:        name,
		Code:        code,
		Type:        channelType,
		Icon:        icon,
		Description: description,
		Status:      int8(status),
		SortOrder:   int(sortOrder),
		IsDefault:   int8(isDefault),
		Config:      string(configJson),
	}

	// 设置基础字段
	channel.FranchiseId = permResult.Admin.FranchiseId
	channel.CreatedBy = permResult.Admin.Username
	channel.UpdatedBy = permResult.Admin.Username
	channel.CreatedAt = time.Now().Unix()
	channel.UpdatedAt = channel.CreatedAt

	// 保存到数据库
	id, err := models.CreatePaymentChannel(channel)
	if err != nil {
		c.handleError(err, "创建支付渠道失败")
		return
	}

	// 如果设置为默认渠道，更新其他渠道为非默认
	if channel.IsDefault == 1 {
		models.SetDefaultPaymentChannel(id)
	}

	c.Data["json"] = map[string]interface{}{
		"success": true,
		"data": map[string]interface{}{
			"id": id,
		},
		"message": "创建支付渠道成功",
	}
	c.ServeJSON()
}

// Update 更新支付渠道信息
func (c *PaymentChannelController) Update() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 获取ID参数
	idStr := c.Ctx.Input.Param(":id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的ID参数",
		}
		c.ServeJSON()
		return
	}

	// 获取支付渠道信息
	channel, err := models.GetPaymentChannelById(id)
	if err != nil || channel == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "支付渠道不存在或获取信息失败",
		}
		c.ServeJSON()
		return
	}

	// 验证加盟商权限
	if permResult.Admin.FranchiseId > 0 && channel.FranchiseId != permResult.Admin.FranchiseId {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无权修改此支付渠道",
		}
		c.ServeJSON()
		return
	}

	// 解析请求体
	var requestData map[string]interface{}
	err = json.Unmarshal(c.Ctx.Input.RequestBody, &requestData)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求数据",
		}
		c.ServeJSON()
		return
	}

	// 更新字段
	updateFields := []string{}

	// 更新名称
	if name, ok := requestData["name"].(string); ok && name != "" {
		channel.Name = name
		updateFields = append(updateFields, "Name")
	}

	// 更新代码（需检查唯一性）
	if code, ok := requestData["code"].(string); ok && code != "" && code != channel.Code {
		existingChannel, _ := models.GetPaymentChannelByCode(code)
		if existingChannel != nil && existingChannel.Id > 0 && existingChannel.Id != id {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "支付渠道代码已存在",
			}
			c.ServeJSON()
			return
		}
		channel.Code = code
		updateFields = append(updateFields, "Code")
	}

	// 更新类型
	if channelType, ok := requestData["type"].(string); ok {
		channel.Type = channelType
		updateFields = append(updateFields, "Type")
	}

	// 更新图标
	if icon, ok := requestData["icon"].(string); ok {
		channel.Icon = icon
		updateFields = append(updateFields, "Icon")
	}

	// 更新描述
	if description, ok := requestData["description"].(string); ok {
		channel.Description = description
		updateFields = append(updateFields, "Description")
	}

	// 更新状态
	if status, ok := requestData["status"].(float64); ok {
		channel.Status = int8(status)
		updateFields = append(updateFields, "Status")
	}

	// 更新排序
	if sortOrder, ok := requestData["sort_order"].(float64); ok {
		channel.SortOrder = int(sortOrder)
		updateFields = append(updateFields, "SortOrder")
	}

	// 更新是否默认
	isDefaultChanged := false
	if isDefault, ok := requestData["is_default"].(float64); ok {
		oldDefault := channel.IsDefault
		channel.IsDefault = int8(isDefault)
		updateFields = append(updateFields, "IsDefault")
		isDefaultChanged = (oldDefault != channel.IsDefault) && channel.IsDefault == 1
	}

	// 提取配置字段（移除标准字段后的所有内容）
	configData := make(map[string]interface{})
	standardFields := []string{"id", "name", "code", "icon", "description", "status", "sort_order", "is_default", "created_at", "updated_at", "type"}

	// 解析现有配置
	if channel.Config != "" {
		json.Unmarshal([]byte(channel.Config), &configData)
	}

	// 添加/更新新的配置字段
	for key, value := range requestData {
		isStandardField := false
		for _, field := range standardFields {
			if key == field {
				isStandardField = true
				break
			}
		}
		if !isStandardField {
			configData[key] = value
		}
	}

	// 序列化配置数据
	configJson, err := json.Marshal(configData)
	if err != nil {
		c.handleError(err, "序列化配置数据失败")
		return
	}
	channel.Config = string(configJson)
	updateFields = append(updateFields, "Config")

	// 更新修改者信息
	channel.UpdatedBy = permResult.Admin.Username
	channel.UpdatedAt = time.Now().Unix()
	updateFields = append(updateFields, "UpdatedBy", "UpdatedAt")

	// 保存到数据库
	err = models.UpdatePaymentChannel(channel, updateFields...)
	if err != nil {
		c.handleError(err, "更新支付渠道失败")
		return
	}

	// 如果设置为默认渠道，更新其他渠道为非默认
	if isDefaultChanged {
		models.SetDefaultPaymentChannel(id)
	}

	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "更新支付渠道成功",
	}
	c.ServeJSON()
}

// Delete 删除支付渠道
func (c *PaymentChannelController) Delete() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 获取ID参数
	idStr := c.Ctx.Input.Param(":id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的ID参数",
		}
		c.ServeJSON()
		return
	}

	// 获取支付渠道信息
	channel, err := models.GetPaymentChannelById(id)
	if err != nil || channel == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "支付渠道不存在或获取信息失败",
		}
		c.ServeJSON()
		return
	}

	// 验证加盟商权限
	if permResult.Admin.FranchiseId > 0 && channel.FranchiseId != permResult.Admin.FranchiseId {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无权删除此支付渠道",
		}
		c.ServeJSON()
		return
	}

	// 删除支付渠道
	err = models.DeletePaymentChannel(id)
	if err != nil {
		c.handleError(err, "删除支付渠道失败")
		return
	}

	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "删除支付渠道成功",
	}
	c.ServeJSON()
}

// TestConnection 测试支付渠道连接
func (c *PaymentChannelController) TestConnection() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 获取ID参数
	idStr := c.Ctx.Input.Param(":id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的ID参数",
		}
		c.ServeJSON()
		return
	}

	// 获取支付渠道信息
	channel, err := models.GetPaymentChannelById(id)
	if err != nil || channel == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "支付渠道不存在或获取信息失败",
		}
		c.ServeJSON()
		return
	}

	// 验证加盟商权限
	if permResult.Admin.FranchiseId > 0 && channel.FranchiseId != permResult.Admin.FranchiseId {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无权测试此支付渠道",
		}
		c.ServeJSON()
		return
	}

	// 测试连接
	err = channel.TestConnection()
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "测试连接失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "测试连接成功",
	}
	c.ServeJSON()
}
